package com.geo.content.service;

import com.geo.content.dto.ContentGenerationRequest;
import com.geo.content.dto.ContentGenerationResponse;
import com.geo.content.dto.ContentListResponse;
import com.geo.content.entity.MultimodalContent;
import com.geo.content.mapper.MultimodalContentMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 内容服务类
 */
@Slf4j
@Service
public class ContentService {
    
    private static final Logger logger = LoggerFactory.getLogger(ContentService.class);
    
    @Autowired
    private MultimodalContentMapper contentMapper;
    
    @Autowired
    private ContentGenerationService contentGenerationService;
    
    /**
     * 获取用户内容列表
     */
    public ContentListResponse getUserContentList(String userId, Integer page, Integer pageSize) {
        List<MultimodalContent> contents = contentMapper.findByUserId(userId);
        
        // 分页处理
        int start = (page - 1) * pageSize;
        int end = Math.min(start + pageSize, contents.size());
        List<MultimodalContent> pagedContents = contents.subList(start, end);
        
        // 转换为DTO
        List<ContentListResponse.ContentItem> contentItems = pagedContents.stream()
                .map(this::convertToContentItem)
                .collect(Collectors.toList());
        
        return new ContentListResponse(contentItems, (long) contents.size(), page, pageSize);
    }
    
    /**
     * 根据内容类型获取内容列表
     */
    public List<MultimodalContent> getContentByType(String contentType) {
        return contentMapper.findByContentType(contentType);
    }
    
    /**
     * 根据状态获取内容列表
     */
    public List<MultimodalContent> getContentByStatus(String status) {
        return contentMapper.findByStatus(status);
    }
    
    /**
     * 根据关键词搜索内容
     */
    public List<MultimodalContent> searchContentByKeyword(String keyword) {
        return contentMapper.findByKeyword(keyword);
    }
    
    /**
     * 更新内容状态
     */
    public boolean updateContentStatus(String contentId, String status) {
        return contentMapper.updateStatus(contentId, status) > 0;
    }
    
    /**
     * 增加内容浏览次数
     */
    public boolean incrementViewCount(String contentId) {
        return contentMapper.incrementViewCount(contentId) > 0;
    }
    
    /**
     * 获取热门内容
     */
    public List<MultimodalContent> getPopularContent(int limit) {
        return contentMapper.findPopularContent(limit);
    }
    
    /**
     * 根据质量分数获取内容
     */
    public List<MultimodalContent> getHighQualityContent(Double minScore) {
        return contentMapper.findByQualityScore(minScore);
    }
    
    /**
     * 生成内容
     */
    public ContentGenerationResponse generateContent(ContentGenerationRequest request) {
        return contentGenerationService.generateContent(request);
    }
    
    /**
     * 异步生成内容
     */
    public ContentGenerationResponse generateContentAsync(ContentGenerationRequest request) {
        try {
            return contentGenerationService.generateContentAsync(request).get();
        } catch (Exception e) {
            throw new RuntimeException("异步生成内容失败", e);
        }
    }
    
    /**
     * 批量生成内容
     */
    public List<ContentGenerationResponse> batchGenerateContent(ContentGenerationRequest request) {
        return contentGenerationService.batchGenerateContent(List.of(request));
    }
    
    /**
     * 删除内容
     */
    public boolean deleteContent(String contentId) {
        MultimodalContent content = contentMapper.selectById(contentId);
        if (content != null) {
            // content.setDeleted(1); // 1表示已删除
            // content.setUpdatedAt(LocalDateTime.now());
            return contentMapper.deleteById(contentId) > 0;
        }
        return false;
    }
    
    /**
     * 获取内容详情
     */
    public MultimodalContent getContentById(String contentId) {
        return contentMapper.selectById(contentId);
    }
    
    /**
     * 转换实体为DTO
     */
    private ContentListResponse.ContentItem convertToContentItem(MultimodalContent content) {
        ContentListResponse.ContentItem item = new ContentListResponse.ContentItem();
        item.setId(content.getId());
        item.setTitle(content.getTitle());
        item.setContentType(content.getContentType() != null ? content.getContentType().name() : "");
        item.setStatus(content.getStatus() != null ? content.getStatus().name() : "");
        // 假设关键词以JSON格式存储，这里需要解析
        // item.setKeywords(parseKeywords(content.getKeywords()));
        item.setQualityScore(content.getQualityScore());
        item.setCreatedAt(content.getCreatedAt());
        item.setUpdatedAt(content.getUpdatedAt());
        item.setCreatedBy(content.getMerchantId()); // 使用merchantId作为createdBy
        item.setViewCount(content.getViewCount() != null ? content.getViewCount().intValue() : 0);
        item.setSummary(content.getDescription()); // 使用description作为summary
        return item;
    }
    
    /**
     * 获取内容列表 - Controller版本
     */
    public ContentListResponse getContentList(String merchantId, int page, int size, String status, String contentType, String keyword) {
        return getUserContentList(merchantId, page, size);
    }
    
    /**
     * 获取内容详情 - Controller版本
     */
    public MultimodalContent getContentDetail(String contentId, String merchantId) {
        return contentMapper.selectById(contentId);
    }
    
    /**
     * 更新内容 - Controller版本
     */
    public MultimodalContent updateContent(String contentId, MultimodalContent updatedContent, String merchantId) {
        MultimodalContent content = contentMapper.selectById(contentId);
        if (content != null) {
            content.setTitle(updatedContent.getTitle());
            content.setDescription(updatedContent.getDescription());
            content.setUpdatedAt(LocalDateTime.now());
            contentMapper.updateById(content);
            return content;
        }
        return null;
    }
    
    /**
     * 删除内容 - Controller版本
     */
    public boolean deleteContent(String contentId, String merchantId) {
        return deleteContent(contentId);
    }
    
    /**
     * 发布内容
     */
    public boolean publishContent(String contentId, List<String> platforms, String merchantId) {
        return updateContentStatus(contentId, "PUBLISHED");
    }
    
    /**
     * 获取内容版本
     */
    public List<MultimodalContent> getContentVersions(String contentId, String merchantId) {
        return List.of(getContentById(contentId));
    }
    
    /**
     * 审核内容
     */
    public boolean reviewContent(String contentId, String action, String comment, String merchantId) {
        return updateContentStatus(contentId, "REVIEWED");
    }
}